﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Micro.AspNetCore;
using Micro.Core.Configs;
using Micro.Core.Packages;
using Micro.Modules;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HostOptions = Micro.Core.Options.HostOptions;


namespace Micro.Hosting
{
    public static class HostBuilderExtensions
    {
        /// <summary>
        /// 基本配置，如读取Configs配置
        /// </summary>
        /// <param name="webApplicationBuilder"></param>
        /// <returns></returns>
        public static WebApplicationBuilder InitBuilder(this WebApplicationBuilder webApplicationBuilder)
        {
            var webHost = webApplicationBuilder.WebHost;
            var services = webApplicationBuilder.Services;
            webHost.AddJsonConfigs(webApplicationBuilder.Services);
            services.AddConfigOptions(webApplicationBuilder.Configuration);

            
            return webApplicationBuilder;
        }


        public static void UseHostBuild(this WebApplicationBuilder webApplicationBuilder)
        {
            IServiceProvider provider = webApplicationBuilder.Services.BuildServiceProvider();

            BasePackage[] packs = provider.GetAllPacks();
            foreach (BasePackage pack in packs)
            {
                pack.UseHostBuilder(webApplicationBuilder.Host, provider);
            }
        }

       


        private static IWebHostBuilder AddJsonConfigs(this IWebHostBuilder hostBuilder, IServiceCollection service)
        {
            var files = Directory.GetFiles(AppsettingConfigs.ConfigsDir, "*.json");


            var configBuilder = new ConfigurationBuilder()
                .SetBasePath(System.Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json", false);

            foreach (var f in files)
            {
                var fi = new FileInfo(f);
                configBuilder.AddJsonFile($"{AppsettingConfigs.ConfigsDir}/{fi.Name}");
            }

            var environmentVariable = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            if (environmentVariable.NotNull())
            {
                configBuilder.AddJsonFile($"appsettings.{environmentVariable}.json", false);
            }

            var config = configBuilder.Build();

            hostBuilder.UseConfiguration(config);

            //var hostOptions = new HostOptions();
            //config.GetSection("Host").Bind(hostOptions);

            ////设置默认端口
            //if (hostOptions.Urls.IsNull())
            //    hostOptions.Urls = "http://*:5500";
            //hostBuilder.UseUrls(hostOptions.Urls);

            //service.AddSingleton(hostOptions);
            return hostBuilder;
        }

        

    }
}
